/*
 * Copyright (C) 2022 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import { GroupType, OperateRequestBody } from './SpStatisticsHttpBean';

export function conversionChartPoints(requestBody: OperateRequestBody, pageDates: any) {
  let datePoints = ordinaryChartDataGroup(requestBody);
  let typeDate: any = {};
  let keys = Object.keys(pageDates);
  let result: any = {};
  keys.forEach((key) => {
    typeDate[key] = JSON.parse(JSON.stringify(datePoints));
    pageDates[key]?.forEach((chartData: any) => {
      let ts = ConvertTimeFormat(chartData.date, requestBody.interval, true);
      typeDate[key][ts] = chartData.value;
    });
    result[key] = [];
    let values = Object.values(typeDate[key]);
    Object.keys(typeDate[key]).forEach((keyTs, index) => {
      let timePoint = ConvertTimeFormat(keyTs, requestBody.interval, false);
      result[key].push({
        date: timePoint,
        value: values[index],
      });
    });
  });
  return result;
}

export function conversionChartPointsAi(requestBody: OperateRequestBody, pageDates: any) {
  let datePoints = ordinaryChartDataGroup(requestBody);
  let typeDate: any = {};
  let keys = Object.keys(pageDates);
  let result: any = {};
  keys.forEach((key) => {
    typeDate[key] = JSON.parse(JSON.stringify(datePoints));
    pageDates[key]?.forEach((chartData: any) => {
      let ts = ConvertTimeFormat(chartData.date, requestBody.interval, true);
      typeDate[key][ts] = {
        value: chartData.value,
        thirdCat: chartData.thirdCat
      }
    });
    result[key] = [];
    let values = Object.values(typeDate[key]);
    Object.keys(typeDate[key]).forEach((keyTs, index) => {
      let timePoint = ConvertTimeFormat(keyTs, requestBody.interval, false);
      result[key].push({
        date: timePoint,
        // @ts-ignore
        value: values[index].value || 0,
        // @ts-ignore
        thirdCat:key
      });
    });
  });
  return result;
}

export function ordinaryChartDataGroup(requestBody: OperateRequestBody) {
  let startNs = requestBody.startTime;
  let endNs = requestBody.endTime;
  let dayTs = 3600000 * 24;
  if (endNs - startNs <= dayTs) {
    let currentDate = new Date();
    let fullYear = currentDate.getFullYear();
    let fullMonth = currentDate.getMonth();
    let fullDay = currentDate.getDate();
    let fullHours = currentDate.getHours();
    let currentDateTs = new Date(fullYear, fullMonth, fullDay).getTime();
    if (currentDateTs === startNs) {
      endNs = new Date(fullYear, fullMonth, fullDay, fullHours).getTime();
    } else {
      endNs = startNs + dayTs;
    }
  }
  let datePoints: any = {};
  switch (requestBody.interval) {
    case GroupType.SECOND:
      let secondInterval = 1000;
      let secondIndex = 0;
      datePoints = {};
      if (endNs - startNs >= secondInterval) {
        let breakPoint = true;
        while (breakPoint) {
          let pointNs = startNs + secondIndex * secondInterval;
          if (pointNs > endNs) {
            breakPoint = false;
          } else {
            let date = new Date(pointNs);
            let localDate = date.toLocaleDateString().replace(/\//g, '-') + ' ' + date.toTimeString().substr(0, 8);
            let dataArr = localDate.split(/[- : \/]/);
            let dateStr = new Date(
              Number(dataArr[0]),
              Number(dataArr[1]) - 1,
              Number(dataArr[2]),
              Number(dataArr[3]),
              Number(dataArr[4]),
              Number(dataArr[5])
            );
            let pointKey = Date.parse(dateStr.toString());
            datePoints[pointKey] = 0;
            secondIndex++;
          }
        }
      } else {
        let date = new Date(requestBody.startTime);
        let localDate = date.toLocaleDateString().replace(/\//g, '-') + ' ' + date.toTimeString().substr(0, 8);
        let dataArr = localDate.split(/[- : \/]/);
        let dateStr = new Date(
          Number(dataArr[0]),
          Number(dataArr[1]) - 1,
          Number(dataArr[2]),
          Number(dataArr[3]),
          Number(dataArr[4]),
          Number(dataArr[5])
        );
        let pointKey = Date.parse(dateStr.toString());
        datePoints[pointKey] = 0;
      }
      break;
    case GroupType.MINUTE:
      let minuteInterval = 60000;
      let minuteIndex = 0;
      datePoints = {};
      if (endNs - startNs >= minuteInterval) {
        let breakPoint = true;
        while (breakPoint) {
          let pointNs = startNs + minuteIndex * minuteInterval;
          if (pointNs > endNs) {
            breakPoint = false;
          } else {
            let date = new Date(pointNs);
            let localDate = date.toLocaleDateString().replace(/\//g, '-') + ' ' + date.toTimeString().substr(0, 8);
            let dataArr = localDate.split(/[- : \/]/);
            let dateStr = new Date(
              Number(dataArr[0]),
              Number(dataArr[1]) - 1,
              Number(dataArr[2]),
              Number(dataArr[3]),
              Number(dataArr[4])
            );
            let pointKey = Date.parse(dateStr.toString());
            datePoints[pointKey] = 0;
            minuteIndex++;
          }
        }
      } else {
        let date = new Date(requestBody.startTime);
        let localDate = date.toLocaleDateString().replace(/\//g, '-') + ' ' + date.toTimeString().substr(0, 8);
        let dataArr = localDate.split(/[- : \/]/);
        let dateStr = new Date(
          Number(dataArr[0]),
          Number(dataArr[1]) - 1,
          Number(dataArr[2]),
          Number(dataArr[3]),
          Number(dataArr[4])
        );
        let pointKey = Date.parse(dateStr.toString());
        datePoints[pointKey] = 0;
      }
      break;
    case GroupType.HOUR:
      let hourInterval = 3600000;
      let hourIndex = 0;
      datePoints = {};
      if (endNs - startNs >= hourInterval) {
        let breakPoint = true;
        while (breakPoint) {
          let pointNs = startNs + hourIndex * hourInterval;
          if (pointNs > endNs) {
            breakPoint = false;
          } else {
            let date = new Date(pointNs);
            let localDate = date.toLocaleDateString().replace(/\//g, '-') + ' ' + date.toTimeString().substr(0, 8);
            let dataArr = localDate.split(/[- : \/]/);
            let dateStr = new Date(Number(dataArr[0]), Number(dataArr[1]) - 1, Number(dataArr[2]), Number(dataArr[3]));
            let pointKey = Date.parse(dateStr.toString());
            datePoints[pointKey] = 0;
            hourIndex++;
          }
        }
      } else {
        let date = new Date(requestBody.startTime);
        let localDate = date.toLocaleDateString().replace(/\//g, '-') + ' ' + date.toTimeString().substr(0, 8);
        let dataArr = localDate.split(/[- : \/]/);
        let dateStr = new Date(Number(dataArr[0]), Number(dataArr[1]) - 1, Number(dataArr[2]), Number(dataArr[3]));
        let pointKey = Date.parse(dateStr.toString());
        datePoints[pointKey] = 0;
      }
      break;
    case GroupType.DAY:
      let dayInterval = 86400000;
      let dayIndex = 0;
      datePoints = {};
      if (endNs - startNs >= dayInterval) {
        let breakPoint = true;
        while (breakPoint) {
          let pointNs = startNs + dayIndex * dayInterval;
          if (pointNs > endNs) {
            breakPoint = false;
          } else {
            let date = new Date(pointNs);
            let localDate = date.toLocaleDateString().replace(/\//g, '-') + ' ' + date.toTimeString().substr(0, 8);
            let dataArr = localDate.split(/[- : \/]/);
            let dateStr = new Date(Number(dataArr[0]), Number(dataArr[1]) - 1, Number(dataArr[2]));
            let pointKey = Date.parse(dateStr.toString());
            datePoints[pointKey] = 0;
            dayIndex++;
          }
        }
      } else {
        let date = new Date(requestBody.startTime);
        let localDate = date.toLocaleDateString().replace(/\//g, '-') + ' ' + date.toTimeString().substr(0, 8);
        let dataArr = localDate.split(/[- : \/]/);
        let dateStr = new Date(Number(dataArr[0]), Number(dataArr[1]) - 1, Number(dataArr[2]));
        let pointKey = Date.parse(dateStr.toString());
        datePoints[pointKey] = 0;
      }
      break;
    case GroupType.MONTH:
      let monthInterval = 2592000000;
      let monthIndex = 0;
      datePoints = {};
      if (endNs - startNs >= monthInterval) {
        let breakPoint = true;
        while (breakPoint) {
          let pointNs = startNs + monthIndex * monthInterval;
          if (pointNs > endNs) {
            breakPoint = false;
          } else {
            let date = new Date(pointNs);
            let localDate = date.toLocaleDateString().replace(/\//g, '-') + ' ' + date.toTimeString().substr(0, 8);
            let dataArr = localDate.split(/[- : \/]/);
            let dateStr = new Date(Number(dataArr[0]), Number(dataArr[1]) - 1);
            let pointKey = Date.parse(dateStr.toString());
            datePoints[pointKey] = 0;
            monthIndex++;
          }
        }
      } else {
        let date = new Date(requestBody.startTime);
        let localDate = date.toLocaleDateString().replace(/\//g, '-') + ' ' + date.toTimeString().substr(0, 8);
        let dataArr = localDate.split(/[- : \/]/);
        let dateStr = new Date(Number(dataArr[0]), Number(dataArr[1]) - 1);
        let pointKey = Date.parse(dateStr.toString());
        datePoints[pointKey] = 0;
      }
      break;
    case GroupType.YEAR:
      let yearInterval = 31536000000;
      let yearIndex = 0;
      datePoints = {};
      if (endNs - startNs >= yearInterval) {
        let breakPoint = true;
        while (breakPoint) {
          let pointNs = startNs + yearIndex * yearInterval;
          if (pointNs > endNs) {
            breakPoint = false;
          } else {
            let date = new Date(pointNs);
            let localDate = date.toLocaleDateString().replace(/\//g, '-') + ' ' + date.toTimeString().substr(0, 8);
            let dataArr = localDate.split(/[- : \/]/);
            let dateStr = new Date(dataArr[0]);
            let pointKey = Date.parse(dateStr.toString());
            datePoints[pointKey] = 0;
            yearIndex++;
          }
        }
      } else {
        let date = new Date(requestBody.startTime);
        let localDate = date.toLocaleDateString().replace(/\//g, '-') + ' ' + date.toTimeString().substr(0, 8);
        let dataArr = localDate.split(/[- : \/]/);
        datePoints[Number(dataArr[0])] = 0;
      }
      break;
    default:
      break;
  }
  return datePoints;
}

export function ConvertTimeFormat(time: string, groupType: GroupType, transformType?: boolean) {
  let dataArr = [];
  let dateStr: Date;
  let ts: number = 0;
  let dateTime: string = '';
  let totalDate = new Date();
  let year = 0;
  let month = 0;
  let date = 0;
  let hours = 0;
  let minutes = 0;
  let seconds = 0;
  if (!transformType) {
    totalDate = new Date(Number(time));
    year = totalDate.getFullYear();
    month = totalDate.getMonth() + 1;
    date = totalDate.getDate();
    hours = totalDate.getHours();
    minutes = totalDate.getMinutes();
    seconds = totalDate.getSeconds();
  }
  switch (groupType) {
    case GroupType.YEAR:
      if (transformType) {
        dataArr = time.split(/[- : \/]/);
        dateStr = new Date(dataArr[0]);
        ts = Date.parse(dateStr.toString());
      } else {
        dateTime = year + '';
      }
      break;
    case GroupType.MONTH:
      if (transformType) {
        dataArr = time.split(/[- : \/]/);
        dateStr = new Date(Number(dataArr[0]), Number(dataArr[1]) - 1);
        ts = Date.parse(dateStr.toString());
      } else {
        dateTime = year + '-' + month;
      }
      break;
    case GroupType.DAY:
      if (transformType) {
        dataArr = time.split(/[- : \/]/);
        dateStr = new Date(Number(dataArr[0]), Number(dataArr[1]) - 1, Number(dataArr[2]));
        ts = Date.parse(dateStr.toString());
      } else {
        dateTime = year + '-' + month + '-' + date;
      }
      break;
    case GroupType.HOUR:
      if (transformType) {
        dataArr = time.split(/[- : \/]/);
        dateStr = new Date(Number(dataArr[0]), Number(dataArr[1]) - 1, Number(dataArr[2]), Number(dataArr[3]));
        ts = Date.parse(dateStr.toString());
      } else {
        dateTime = year + '-' + month + '-' + date + ' ' + hours;
      }

      break;
    case GroupType.MINUTE:
      if (transformType) {
        dataArr = time.split(/[- : \/]/);
        dateStr = new Date(
          Number(dataArr[0]),
          Number(dataArr[1]) - 1,
          Number(dataArr[2]),
          Number(dataArr[3]),
          Number(dataArr[4])
        );
        ts = Date.parse(dateStr.toString());
      } else {
        dateTime = year + '-' + month + '-' + date + ' ' + hours + ':' + minutes;
      }

      break;
    case GroupType.SECOND:
      if (transformType) {
        dataArr = time.split(/[- : \/]/);
        dateStr = new Date(
          Number(dataArr[0]),
          Number(dataArr[1]) - 1,
          Number(dataArr[2]),
          Number(dataArr[3]),
          Number(dataArr[4]),
          Number(dataArr[5])
        );
        ts = Date.parse(dateStr.toString());
      } else {
        dateTime = year + '-' + month + '-' + date + ' ' + hours + ':' + minutes + ':' + seconds;
      }
      break;
  }
  return transformType ? ts : dateTime;
}

// function date

export interface StatisticsPageData {
  key: string;
  date: string;
  num: number;
  index: number;
}
